package com.kk.license.server.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.kk.license.common.LicenseCreator;
import com.kk.license.common.bean.LicenseCheckModel;
import com.kk.license.common.bean.LicenseCreatorParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.sql.Date;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Base64;

/**
 * @Description TODO
 * @Author wangkang
 * @Create 2023-07-19 9:37
 * @Version 1.0
 */
@Slf4j
public class LicenseUtils {
    /**
     * license生成路径
     */
    private static final String LICENSE_PATH = System.getProperty("user.dir") + "/license.lic";
    /**
     * 私钥路径
     */
    private static final String PRIVATE_KEYS_STORE_PATH = System.getProperty("user.dir") + "/privateKeys.keystore";

    private static LicenseCreatorParam param = new LicenseCreatorParam();

    static {
        param.setSubject("license");
        param.setPrivateAlias("privateKey");
        param.setKeyPass("private-password-2fZULeK8K6Wk2g7");
        param.setStorePass("public-password-bDq1BUKu6lQdWQj");
        param.setExpiryTime(Date.from(LocalDateTime.of(2099,12,31,23,59,59).atZone(ZoneId.systemDefault()).toInstant()));
    }

    /**
     * 生成license文件
     * @param machineCode 机器码
     */
    public static void generateLicense(String machineCode) {

        byte[] decode = Base64.getDecoder().decode(machineCode);
        LicenseCheckModel licenseCheckModel = JSON.parseObject(decode).toJavaObject(LicenseCheckModel.class);
        //设置允许添加设备通道数
        licenseCheckModel.setAllowChannel(500);
        generateLicense(licenseCheckModel);
    }

    /**
     * 生成license文件
     * @param licenseCheckModel 授权参数
     */
    public static void generateLicense(LicenseCheckModel licenseCheckModel) {
        param.setLicenseCheckModel(licenseCheckModel);

        if (!StringUtils.hasText(param.getLicensePath())) {
            param.setLicensePath(LICENSE_PATH);
        }
        param.setPrivateKeysStorePath(PRIVATE_KEYS_STORE_PATH);
        LicenseCreator licenseCreator = new LicenseCreator(param);
        boolean result = licenseCreator.generateLicense();

        if (result) {
            log.info("license生成路径:{}",param.getLicensePath());
        } else {
            log.error("证书文件生成失败！");
        }
    }
}
